package com.gxa.realm;


import com.gxa.entity.User;
import com.gxa.mapper.UserMapper1;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * 认证
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {
    //    @Autowired
//    private ShiroService shiroService;
    @Resource
    private UserMapper1 userMapper1;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        SysUserEntity user = (SysUserEntity)principals.getPrimaryPrincipal();
//        Long userId = user.getUserId();

        //用户权限列表
//        Set<String> permsSet = shiroService.getUserPermissions(userId);

//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.setStringPermissions(permsSet);
//        return info;

        System.out.println("------------------OAuth2Realm--授权方法----------------");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> perms = new HashSet<>();
        User user = (User) principals.getPrimaryPrincipal();
        if("admin".equals(user.getUserName())){
            perms.add("emp:list");
            perms.add("emp:add");
            perms.add("emp:update");
            perms.add("emp:delete");
        }else if("zs".equals(user.getUserName())){
            perms.add("emp:list");
            perms.add("emp:add");
            perms.add("emp:update");
        }else if("ls".equals(user.getUserName())){
            perms.add("emp:list");
        }

        info.addStringPermissions(perms);
        System.out.println("授予的权限：--"+perms);
        return info;

    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        String accessToken = (String) token.getPrincipal();
        //根据accessToken，查询用户信息
//        SysUserTokenEntity tokenEntity = shiroService.queryByToken(accessToken);
        //token失效
//        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
//            throw new IncorrectCredentialsException("token失效，请重新登录");
//        }

        //查询用户信息
//        SysUserEntity user = shiroService.queryUser(tokenEntity.getUserId());
        //账号锁定
//        if(user.getStatus() == 0){
//            throw new LockedAccountException("账号已被锁定,请联系管理员");
//        }

//        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
//        return info;


        System.out.println("------------------OAuth2Realm--认证方法----------------");
        String token = (String) authenticationToken.getPrincipal();
        User user = userMapper1.queryByToken(token);
        System.out.println("根据token 查询 到的用户信息 ----"+user);// 实际有分布式session问题  都是从 公共的 redis 缓存中拿
        if(user != null){
            System.out.println("认证 token success !!");
        }else {
            throw new IncorrectCredentialsException("token失效!!");
        }

        //也可以增加ip校验
        //HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //            String ip = IPUtils.getIpAddr(request);
        //            if (!StringUtils.equals(ip, user.getLoginIp())) {
        //                throw new IncorrectCredentialsException("非法使用token");
        //            }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, token, this.getName());
        return info;
    }
}
